'use strict'

###*
 # @ngdoc function
 # @name xoceanApp.controller:SubjectsCtrl
 # @description
 # # SubjectsCtrl
 # Controller of the page named '我的专题'
###
angular.module('xoceanApp')
  .controller 'SubjectsCtrl', ($scope, $filter, $window, $state, Subject, publishedSubjects) ->
    currentTab = 'published'
    publishedSubjects = $filter('orderBy') publishedSubjects, 'postime', true
    unPublishedSubjects = $filter('orderBy') Subject.getUnpublishedSubjects(), 'postime', true
    _subjects = []

    $scope.isActive = (tab)->
      return tab is currentTab

    $scope.pageChanged = ->
      $scope.subjects = _subjects.slice ($scope.currentPage - 1) * 16 , $scope.currentPage * 16 
      return

    $scope.onclickTab = (tab)->
      currentTab = tab
      if currentTab is 'unPublished'
        _subjects = unPublishedSubjects
      else
        _subjects = publishedSubjects
      $scope.currentPage = 1
      $scope.totalItems = _subjects.length
      $scope.subjects = _subjects.slice(0,16)

      return

    $scope.onclickTab(currentTab)

    $scope.deleteSubject = (id, index)->
      result = $window.confirm('确认删除？')
      return unless result
      console.log 'Delete subject which id is ' + id
      Subject.deleteSubjectById(id, true).then ->
        $scope.subjects.splice(index, 1)
    $scope.showTime = (index)->
      if index is 0
        return true
      prev = $filter('date')($scope.subjects[index - 1]['postime'], 'yyyy-MM-dd')
      current = $filter('date')($scope.subjects[index]['postime'], 'yyyy-MM-dd')
      return  prev isnt current

    $scope.isLast = (index)->
      if index + 1 is $scope.subjects.length
        return true
      current = $filter('date')($scope.subjects[index]['postime'], 'yyyy-MM-dd')
      next = $filter('date')($scope.subjects[index + 1]['postime'], 'yyyy-MM-dd')
      return current isnt next
